package session.stateless.FRM;

import entity.FRM.CreditAccount;
import entity.CRM.Customer;
import entity.CRM.SaleOrder;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import session.stateless.CRM.CustomerBeanLocal;

@Stateless
public class CreditAccountBean implements CreditAccountBeanLocal {
    @PersistenceContext 
    private EntityManager em; 
    
    public CreditAccount createCreditAccount(Double deposit, Double creditLimit, Double creditBalance, Double creditDiscount, Long creditPeriod, Long netPeriod) {
        CreditAccount creditAccount = new CreditAccount();
        creditAccount.setDeposit(deposit);
        creditAccount.setCreditLimit(creditLimit);
        creditAccount.setCreditBalance(creditBalance);
        creditAccount.setCreditDiscount(creditDiscount);
        creditAccount.setCreditPeriod(creditPeriod);
        creditAccount.setNetPeriod(netPeriod);
        
        em.persist(creditAccount);
        return creditAccount;
        
    }

    public void addDeposit(Customer customer, Double depositAdd) {
        System.out.println("test1"+customer.getSaleLeadName());        
        CreditAccount creditAccount = customer.getCreditAccount();
        System.out.println("test2:deposit"+creditAccount.getDeposit()+"  limit"+creditAccount.getCreditLimit());
        System.out.println("DepositAdd " + depositAdd);
        creditAccount.setDeposit((creditAccount.getDeposit()+depositAdd));
        creditAccount.setCreditLimit(creditAccount.getCreditLimit()+depositAdd);
        System.out.println("test3: after add, deposit "+creditAccount.getDeposit()+"   limit "+creditAccount.getCreditLimit());
        em.flush();        
        System.out.println("test4: after flush ID "+ creditAccount.getCreditAccountId()+" deposit "+customer.getCreditAccount().getDeposit()+"   limit "+customer.getCreditAccount().getCreditLimit());
        System.out.println("test5: deposit"+customer.getCreditAccount().getDeposit()+"  Limit"+customer.getCreditAccount().getCreditLimit());
    }

    public void modifyCreditBalance_AddSaleOrder(Customer customer, Double totalPrice) {
        CreditAccount creditAccount = customer.getCreditAccount();
        creditAccount.setCreditBalance(totalPrice+creditAccount.getCreditBalance());
        em.flush();
    }

    public void modifyCreditBalance_ReduceSaleOrder(SaleOrder saleOrder, Double oldPrice, Double newPrice) {
        CreditAccount creditAccount = saleOrder.getCustomer().getCreditAccount();
        creditAccount.setCreditBalance(creditAccount.getCreditBalance()-oldPrice+newPrice);
        em.flush();
    }

    public Double isPass_checkCreditBalance(Customer customer) {
        CreditAccount creditAccount = customer.getCreditAccount();
        return creditAccount.getCreditLimit()-creditAccount.getCreditBalance();        
    }
}
